<template>
  <div class="app-container classify-box">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="6" :md="6" :lg="5">
        <!-- 搜索 -->
        <el-input
          v-hasPermi="['inv:sort:query']"
          v-model="searchName"
          placeholder="请输入分类名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 10px"
        />
        <!-- 新增主类 -->
        <div class="add-class" style="margin-bottom: 10px" v-if="isOperation">
          <el-button
            type="primary"
            v-hasPermi="['inv:sort:add']"
            size="mini"
            @click="addParentSort"
            plain
            >新增主类
          </el-button>
          <el-button
           type="success"
            size="mini"
            @click="handdleUnit"
            v-hasPermi="['inv:sort:add']"
            plain
            >计量单位
          </el-button>
           <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              >导入</el-button
            >
              <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              >导出</el-button
            >
        </div>
        <!-- 分类数据 -->
        <Tree
          ref="tree"
          :sortTree="sortTree"
          :loading="loading"
          :isOperation="isOperation"
          :isHeight="isHeight"
          @addSort="addSort"
          @uplateSort="uplateSort"
          @remove="remove"
          @nodeClick="nodeClick"
          :searchName="searchName"
        />
      </el-col>
      <el-col :sm="12" :md="12" :lg="6" :xs="20">
        <div class="sort-content" ref="treeForm">
          <!-- 表单区域 -->
          <el-form
            :model="form"
            :rules="rules"
            ref="form"
            label-width="108px"
            style="margin: 20px 22px 0 20px"
            :disabled="butChange == 'seeStatus'"
          >
            <el-form-item
              label="上级分类ID"
              prop="parentId"
              class="ma-lable"
              style="display: none"
            >
              <el-input v-model="form.parentId"></el-input>
            </el-form-item>
            <el-form-item
              label="上级分类"
              class="ma-lable superior-class"
              v-if="isParentId"
            >
              <el-input v-model="parentName" disabled></el-input>
            </el-form-item>
            <el-form-item label="分类编码" prop="sortCode" class="ma-lable">
              <el-input v-model="form.sortCode"></el-input>
            </el-form-item>
            <el-form-item label="分类名称" prop="sortName" class="ma-lable">
              <el-input v-model="form.sortName"></el-input>
            </el-form-item>
            <el-form-item label="计量单位" prop="unitForm" class="ma-lable">
              <el-select
                v-model="unitForm"
                placeholder="请选择"
                @change="unitChange"
                @click.native="handdleRequestUnit"
              >
                <el-option
                  v-for="(item, index) in unitDate"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                >
                  <span>{{ item.name }}</span>
                  <span>（{{ item.code }}）</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="流水号长度"
              prop="serialLength"
              class="ma-lable"
            >
              <el-input v-model="form.serialLength"></el-input>
            </el-form-item>
            <el-form-item label="供应方式" prop="property" class="ma-lable">
              <el-select v-model="form.supplyType" placeholder="">
                <el-option
                  v-for="item in optionsSupplyType"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <div style="margin-top: 10px">
              <el-form-item label="分类状态" class="ma-lable">
                <el-select v-model="form.status">
                  <el-option label="正常" value="0"></el-option>
                  <el-option label="停用" value="1"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="handle-save">
            <div v-if="butChange == 'addStatus'" style="margin-right: 10px">
              <el-button
                type="primary"
                v-hasPermi="['inv:sort:add']"
                icon="el-icon-edit"
                @click="submitFrom('form', treeNode)"
                >确定
              </el-button>
            </div>
            <div v-if="butChange == 'seeStatus'" style="margin-right: 10px">
              <el-button
                type="success"
                v-hasPermi="['inv:sort:edit']"
                icon="el-icon-edit"
                @click="handleUpdate"
                >修改
              </el-button>
            </div>
            <div v-if="butChange == 'updateStatus'" style="margin-right: 10px">
              <el-button
                type="success"
                v-hasPermi="['inv:sort:edit']"
                icon="el-icon-edit"
                @click="submitFrom('form', treeNode)"
                >保存
              </el-button>
            </div>

            <el-button
              icon="el-icon-refresh"
              @click="reset"
              v-if="butChange == 'addStatus' || butChange == 'updateStatus'"
              >重置</el-button
            >
          </div>
        </div>
      </el-col>
      <el-col :sm="12" :md="12" :lg="6" :xs="20">
        <!-- 计量单位-->
        <Unit
          :inHeight="inHeight"
          :unitTree="unitTree"
          :unitStatus.sync="unitStatus"
          v-show="unitStatus"
          ref="unitTree"
          :codeWidth="codeWidth"
        />
      </el-col>
    </el-row>
        <!-- 物料导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="
          upload.url
        "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listSort,
  addSort,
  updateSort,
  delSort,
  listUnit,
  dictMatching,
  exportSort
} from "../../api/sort"; //接口
import {
  isSerial,
  supParent,
  getCurrentNode,
  setCurrentNode,
} from "../../utils/sort.js"; //js方法
import { getToken } from "@/utils/auth";
import { isDigit } from "@/utils/cingsoft.js";
import Tree from "../../components/Sort/tree.vue"; //分类组件
import Unit from "../../components/Sort/unit.vue"; //计量单位组件
//并行请求
import axios from "axios";
export default {
  name: "Sort",
  data() {
    // 流水号宽度自定义校验
    var validateSerial = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("流水号宽度不能为空"));
      }
      if (!isSerial(value)) {
        callback(new Error("请输入正确流水号宽度"));
      } else {
        callback();
      }
    };
    // 数量小数位数校验
    var validateQuantity = (rule, value, callback) => {
      if (!value) {
        return callback(new Error(""));
      }
      if (!isDigit(value)) {
        callback(new Error(""));
      } else {
        callback();
      }
    };
    // 单价小数位数校验
    var validatePrice = (rule, value, callback) => {
      if (!value) {
        return callback(new Error(""));
      }
      if (!isDigit(value)) {
        callback(new Error(""));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      //分类搜索名称
      searchName: "",
      // 上级分类名称
      parentName: "",
      //父分类id
      parentId: "",
      //上级分类是否显示
      isParentId: true,
      //物料特性/小数位数/规格别名/规格合并只是新增主类时显示
      specialStatus: false,
      //节点是否有高亮属性
      isHeight: false,
      //是否显示分类操作按钮
      isOperation: true,
      //element-ui表头样式
      activeName: "basicinfo",
      //树形数据
      sortTree: [],
      //是否显示分类操作按钮
      isoperation: true,
      //树形节点
      treeNode: "",
      //绑定树形数据名称
      defaultProps: {
        children: "children",
        label: "sortName",
      },
      // 基本信息表单数据
      form: {
        sortCode: "", //编码
        sortName: "", //名称
        status: "0", //状态
        serialLength: "4", //流水号宽度
        supplyType: "0",
      },
      //按钮切换新增/保存
      butChange: "",
      //物料特性组件高度
      inHeight: "",
      // 计量单位
      unitDate: [],
      unitForm: "",
      unitTree: [],
      codeWidth: "", //编码最大高度
      unitStatus: false,
      //供应方式
      optionsSupplyType: [],
        // 物料分类导入参数
      upload: {
        // 是否显示弹出层（物料信息导入）
        open: false,
        // 弹出层标题（物料信息导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        //分类id
        sortId: "",
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/inv/importData",
      },
      // 表单校验
      rules: {
        sortName: [
          {
            required: true,
            message: "分类名称不能为空",
            trigger: "blur",
          },
        ],
        sortCode: [
          {
            required: true,
            message: "分类编码不能为空",
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: "分类状态不能为空",
            trigger: "change",
          },
        ],
        serialLength: [
          {
            required: true,
            validator: validateSerial,
            trigger: "blur",
          },
        ],

        priceDigit: [
          {
            required: true,
            validator: validatePrice,
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    //初始化分类树/计量单位/物料特性
    this.getIntParallel();
    //初始化隐藏上级分类
    this.isParentId = false;
    //初始化parentId
    this.parentId = 0;
    //物料特性字段
    this.specialStatus = true;
    //初始化按钮状态
    this.butChange = "addStatus";
  },
  methods: {
    //初始化并行请求数据
    getIntParallel() {
      const _self = this;
      this.loading = true;
      //并行请求
      axios.all([listSort(), listUnit(), dictMatching("inv_supply_type")]).then(
        axios.spread(function (resTree, resUnit, resSupplyType) {
          if (resTree.code == 200 && resUnit.code == 200) {
            _self.loading = false;
            //分类树
            _self.sortTree = resTree.data;
            //计量单位
            _self.unitDate = JSON.parse(JSON.stringify(resUnit.rows));
            _self.unitTree = resUnit.rows;
            _self.unitDate.unshift({
              name: "无",
              code: "",
            });
            //供应方式
            _self.optionsSupplyType = resSupplyType.data;
          } else {
            _self.msgError("获取数据失败");
          }
        })
      );
    },

    // 获取计量单位
    getUnit() {
      listUnit().then((res) => {
        this.unitDate = JSON.parse(JSON.stringify(res.rows));
        this.unitDate.unshift({
          name: "无",
          code: "",
        });
      });
    },

    //选择计量单位
    unitChange(value) {
      if (this.unitDate.length > 0 && value !== "") {
        let obj = {};
        obj = this.unitDate.find((item) => {
          return item.code === value;
        });
        this.form.unitCode = obj.code; //计量单位编码
        this.form.unitName = obj.name; //计量单位名称
      } else {
        this.form.unitCode = ""; //计量单位编码
        this.form.unitName = ""; //计量单位名称
      }
    },

    //点击计量单位获取接口
    handdleRequestUnit() {
      this.getUnit();
    },

    // 显示计量单位组件
    handdleUnit() {
      this.inHeight = this.$refs.treeForm.offsetHeight;
      this.unitStatus = !this.unitStatus;
      this.getWidth("unitTree");
    },

    // 编码编码宽度
    getWidth(tree) {
      let uWidth;
      if (tree == "unitTree") {
        uWidth = this.unitTree.map((value) => {
          return this.$refs.unitTree.$refs[`unitCode${value.uniqueId}`]
            .offsetWidth;
        });
      }

      uWidth.sort((a, b) => {
        return b - a;
      });
      this.codeWidth = uWidth[0].toString() + "px";
    },

    //添加主分类
    addParentSort() {
      this.reset(); //重置表单内容
      this.isParentId = false; //父类名称为隐藏
      this.parentId = 0; //父类Id为0，代表添加主分类
      this.butChange = "addStatus"; //按钮状态为添加
      this.specialStatus = true; //默认显示物料特性/小数位数
      this.unitForm = ""; //计量单位为空
      this.form.unitCode = ""; //计量单位编码
       this.form.supplyType = "0";
      this.form.unitName = ""; //计量单位名称
      setTimeout(() => {
        this.inHeight = this.$refs.treeForm.offsetHeight.toString(); // 特性组件高度
      }, 50);
    },

    //分类树选中
    nodeClick() {
      this.isHeight = false;
      this.form = Object.assign({}, arguments[0]);
      this.parentId = this.form.parentId; //保存parentId，用来不触发新增按钮form提交
      this.treeNode = arguments[1]; //节点赋值，用来确定添加位置
      // 计量单位
      this.unitForm = this.form.unitCode;
      // 物料特性列表

      this.uplateAdd(arguments[1]); //修改新增公共方法
      if (arguments[0].parentId == 0) {
        //父类Id为0，代表添加主分类
        this.isParentId = false; //父类名称为隐藏
        this.specialStatus = true;
      } else {
        this.isParentId = true;
        this.specialStatus = false;
      }
      this.butChange = "seeStatus";
      setTimeout(() => {
        this.inHeight = this.$refs.treeForm.offsetHeight.toString(); // 特性组件高度
      }, 50);
    },

    // 从查看切换修改按钮
    handleUpdate() {
      this.butChange = "updateStatus";
    },

    //添加子分类
    addSort(node) {
      this.specialStatus = false;
      this.reset(); //重置表单内容
      this.butChange = "addStatus"; //按钮状态为添加
      this.uplateAdd(node); //修改新增公共方法
      this.isParentId = true; //父类名称为显示
      this.parentId = node.data.sortId; //保存parentId，用来不刷新时表单提交
      this.treeNode = node; //节点赋值，用来确定添加位置
      this.form.unitCode = ""; //计量单位编码
      this.form.unitName = ""; //计量单位名称
      setTimeout(() => {
        this.inHeight = this.$refs.treeForm.offsetHeight.toString(); // 特性组件高度
      }, 50);
    },

    //修改分类
    uplateSort(node) {
      this.butChange = "updateStatus"; //按钮状态为保存
      this.uplateAdd(node); //修改新增公共方法
      this.form = Object.assign({}, node.data); //拷贝表单内容，避免影响数据
      this.parentId = this.form.parentId; //保存parentId，用来不触发新增按钮form提交
      this.treeNode = node; //节点赋值，用来确定添加位置
      this.unitChange(node.data.unitCode);
      this.unitForm = node.data.unitCode;
      if (node.data.parentId == 0) {
        //父类Id为0，代表添加主分类
        this.isParentId = false; //父类名称为隐藏
        this.specialStatus = true;
        setTimeout(() => {
          this.inHeight = this.$refs.treeForm.offsetHeight.toString(); // 特性组件高度
        }, 50);
      } else {
        this.isParentId = true;
        this.specialStatus = false;
        setTimeout(() => {
          this.inHeight = this.$refs.treeForm.offsetHeight.toString(); // 特性组件高度
        }, 50);
      }
    },

    // 修改分类新增分类公共方法
    uplateAdd(node) {
      this.$refs.form.resetFields(); //清除表单验证
      // 上级分类高亮
      this.isHeight = true;
      const getNode = [];
      getCurrentNode(node, getNode).then((currentNode) => {
        setCurrentNode(this.$refs.tree.$refs.tree.root, currentNode);
      });

      // 获取上级分类名称
      const name = [];
      const getParentName = supParent(node, name).reverse(); //获取上级分类名称
      const parentName = getParentName.join(" / "); //拼接上级分类名称
      if (node.data.parentId == 0) {
        this.parentName = node.data.sortName; //主类上级分类为自身
      } else if (this.butChange == "addStatus") {
        this.parentName = parentName + " / " + node.data.sortName; //子类上级分类最终结果
      } else {
        this.parentName = parentName;
      }
    },

    //提交表单
    submitFrom(form, node) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.form.parentId = this.parentId; //赋值parentId，用来不刷新时表单提交
          if (this.butChange == "addStatus") {
            //触发新增提交
            addSort(this.form)
              .then((res) => {
                if (res.code == 200) {
                  this.msgSuccess("新增成功");
                  if (this.form.parentId == 0) {
                    this.sortTree.push(res.data);
                  } else {
                    // console.log(node)
                    node.expand();
                    // console.log(res.data)
                    this.$refs.tree.$refs.tree.append(res.data, node); //不刷新更新节点数据
                  }
                  this.reset(); //重置表单
                }
              })
              .catch((err) => {
                this.msgError("新增失败");
              });
          } else {
            this.form.parentId = this.parentId; //赋值parentId，用来不刷新时表单提交
            updateSort(this.form)
              .then((res) => {
                //触发保存提交
                if (res.code == 200) {
                  this.msgSuccess("保存成功");
                  this.form.version = res.data.version; //保存version，用来不刷新修改
                  node.data.sortName = this.form.sortName;
                  node.data.sortCode = this.form.sortCode;
                  node.data.status = this.form.status;
                  node.data.serialLength = this.form.serialLength;
                  node.data.unitCode = this.form.unitCode;
                  node.data.unitName = this.form.unitName;
                  node.data.supplyType= this.form.supplyType;
                  node.data.version = res.data.version;
                }
              })
              .catch((err) => {
                this.msgError("保存失败");
              });
          }
        }
      });
    },

    //移除分类
    remove(node) {
      this.$confirm("确认删除", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delSort(node.data.sortId);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.reset(); //重置表单
            this.isHeight = false;
            this.isParentId = false; //父类名称为隐藏
            this.parentId = 0; //父类Id为0，代表添加主分类
            this.butChange = "addStatus"; //按钮状态为添加
            this.$refs.tree.$refs.tree.remove(node); //移除节点
          }
        });
    },

     //导出
    handleExport() {
      this.$confirm("是否确认导出物料分类?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportSort();
        })
        .then((response) => {
          this.download(response.msg);
        });
    },

    
    // 导入按钮操作
    handleImport() {
      this.upload.title = "物料分类导入";
      this.upload.open = true;
    },

    //下载模板操作
    importTemplate() {
      importMateria({
        sortId: this.upload.sortId,
      }).then((response) => {
        this.download(response.msg);
      });
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {
        dangerouslyUseHTMLString: true,
      });
      this.getIntParallel();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },


    // 表单重置
    reset() {
      this.form.sortName = "";
      this.form.sortCode = "";
      this.form.serialLength = "4";
      this.form.status = "0";
      this.form.featureCode = "";
      this.form.priceDigit = "2";
      // this.form.allowDebt = "0";
      this.form.batchNumber = "0";
      this.unitForm = "";
      this.form.unitCode = "";
      this.form.unitName = "";
      this.form.supplyType = "0"
    },
  },
  components: {
    Tree,
    Unit,
  },
};
</script>
<style lang="scss">
.classify-box {
  padding-bottom: 0px !important;
  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background: none !important;
    color: #1890ff !important;
  }
  .el-button--mini{
    padding: 7px 13px;
  }
  .switch-spc {
    .el-form-item__label {
      line-height: 20px;
    }

    .el-form-item__content {
      line-height: 20px;
    }
  }

  .superior-class {
    .el-input.is-disabled .el-input__inner {
      color: #1890ff !important;
    }
  }

  .sort-content {
    border: 1px solid #ebebeb;
    padding: 10px 12px 10px 10px;
    border-radius: 5px;

    .el-tabs--border-card {
      box-shadow: inherit;
    }

    .el-form-item__label {
      font-weight: normal !important;
    }

    .handle-save {
      margin-top: 20px;
      margin-bottom: 20px;
      margin-right: 22px;
      text-align: right;
      display: flex;
      justify-content: flex-end;
      .el-button--medium {
        padding: 8px;
        font-size: 13px;
      }

      .el-button--info {
        background: #ccc;
      }
    }

    .el-input.is-disabled .el-input__inner {
      color: #333;
    }
  }

  .el-radio__input.is-disabled.is-checked .el-radio__inner {
    background-color: #f5f7fa;
    border-color: #999;
  }

  .el-radio__input.is-disabled + span.el-radio__label {
    color: #333;
    cursor: not-allowed;
  }

  .ma-lable {
    .el-select {
      width: 100%;
    }
  }

  .el-tree-node__children {
    .inal-input {
      .inal-a {
        display: none;
      }
    }
  }
}
</style>
